/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lambkit.web.enjoy;

import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Assign;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import com.lambkit.db.DbPool;
import com.lambkit.db.RowData;

import java.util.List;

/**
 * #findBy(key, size, "table", id=1)
 * <li>#(key.id)</li> #end
 * 
 * @author 孤竹行
 */
//@JFinalDirective("findBy")
public class FindBy extends LambkitDirective {

	@Override
	public void onRender(Env env, Scope scope, Writer writer) {
		// TODO Auto-generated method stub
		String key = getPara(0, scope);
		Integer size = getParaToInt(1, scope, 1);
		String tableName = getPara(2, scope);
		String sql = "select * from " + tableName;
		Assign col = (Assign) exprList.getExpr(3);
		sql += " where " + col.getId() + "=" + col.getRight().toString();
		if(exprList.length() > 4) {
			for (int i = 4; i < exprList.length(); i++) {
				Assign name = (Assign) exprList.getExpr(i);
				sql += " and " + name.getId() + "=" + name.getRight().toString();
			}
		}
		if(size == 1) {
			RowData record = DbPool.use().findFirst(sql);
			scope.set(key, record);
		} else {
			sql += " limit " + size;
			List<RowData> list = DbPool.use().find(sql);
			scope.set(key, list);
		}
		renderBody(env, scope, writer);// 执行自定义标签中包围的 html
	}

	@Override
	public boolean hasEnd() {
		return true;
	}
}
